package sunyu.tools.solr;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.nutz.lang.Lang;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import sunyu.tools.common.JsonTools;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * shiro工具类
 *
 * @author 孙宇
 */
@Component
public class SolrTools {

    public static final String defaultName = "main";
    private static final ConcurrentHashMap<String, SolrClient> solrClientMap = new ConcurrentHashMap<>();
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource(name = "jsonTools")
    private JsonTools jsonTools;

    public SolrClient getClient(String name) {
        return solrClientMap.get(name);
    }

    @PreDestroy
    public void destroy() {
        logger.info("销毁所有solr客户端开始");
        for (Map.Entry<String, SolrClient> entry : solrClientMap.entrySet()) {
            try {
                entry.getValue().close();
            } catch (IOException e) {
                logger.error(ExceptionUtils.getStackTrace(e));
            }
        }
        logger.info("销毁所有solr客户端结束");
    }

    public void addClient(String name,
                          String soleUrl) {
        logger.info("添加一个solr客户端：{}", name);
        if (solrClientMap.containsKey(name)) {
            logger.error("{}已存在！", name);
        } else {
            Map<String, String> urlMap = jsonTools.toMap(soleUrl);
            String solrName = urlMap.get("name");
            String url = urlMap.get("url");//url最后一个字符必须是"/"
            SolrClient client = new HttpSolrClient.Builder(url + solrName).build();
        /*String zkHostString = "zkServerA:2181,zkServerB:2181,zkServerC:2181/solr";
        SolrClient client = new CloudSolrClient.Builder().withZkHost(zkHostString).build();*/
            solrClientMap.put(name, client);
        }
    }

    public <T> T execute(String name,
                         SolrClientCallback<T> action) {
        SolrClient client = getClient(name);
        try {
            return action.doInClient(client);
        } catch (Throwable throwable) {
            throw Lang.wrapThrow(throwable);
        }
    }

}
